from performanceTest import restart_tomcat
import time
import os
import paramiko

#查看启动的服务的端口号
def runPort():
    proshell = "ps -ef | grep nmon | grep -v 'grep'| awk '{{print $2}}'"  # grep -v 反匹配，不匹配-v后面的内容
    stdin, stdout, stderr = sshconnect.exec_command(proshell)
    pronum = stdout.read().decode('utf-8')  # 转码
    print('新启动的nmon端口号为=》%s'% pronum)

#判断是否已有启动的服务，若有杀掉
def killPID():
    print('检查是否有启动的nmon服务')
    # grep -v 反匹配，不匹配-v后面的内容
    proshell = "ps -ef | grep nmon | grep -v 'grep' | awk '{{print $2}}'"  # grep -v 反匹配，不匹配-v后面的内容
    stdin, stdout, stderr = sshconnect.exec_command(proshell)
    pronum = stdout.read().decode('utf-8')  # 转码
    if not pronum:
        print('无启动的nmon服务！')
    else:
        print('原启动的tomcat端口号为：%s' % pronum)
        sshconnect.exec_command('kill -9 {}'.format(pronum))  # 杀死进程号
        print('已杀死已有nmon服务%s' % pronum)


#启动AP服务器上的nmon
cur_time = time.strftime('%y-%m-%d %X')
connAP = restart_tomcat.Mytomcat('172.20.20.6', 22, 'root', 'Dhcc-123@6')
sshconnect = connAP.serverconnect()
killPID()
#下载结果文件到本地
# connAP.download(r'/home/nmonResult/',r'D:\data\DHCCZ\task\性能测试\测试结果\nmon结果图\AP',sshconnect)
sshconnect.exec_command('cd /home/nmonResult && rm -rf *')
print('%s启动应用服务器nmon'%cur_time)
#启动nmon
sshconnect.exec_command('cd /opt/nmon && ./nmon -s5 -c185 -f -m /home/nmonResult')
time.sleep(2)
runPort()
sshconnect.close()

#启动DB服务器上的nmom
cur_time = time.strftime('%y-%m-%d %X')
connDB = restart_tomcat.Mytomcat('172.20.20.8', 22, 'root', 'Dhcc-123@8')
sshconnect= connDB.serverconnect()
killPID()
#下载结果文件到本地
# connDB.download(r'/home/nmonResult/',r'D:\data\DHCCZ\task\性能测试\测试结果\nmon结果图\DB',sshconnect)
sshconnect.exec_command('cd /home/nmonResult && rm -rf *')
print('%s启动数据库服务器nmon'%cur_time)
#启动nmon
sshconnect.exec_command('cd /opt/nmon && ./nmon -s5 -c185 -f -m /home/nmonResult')
time.sleep(2)
runPort()
sshconnect.close()


# print(os.system('ipconfig'))
# os.system('scp -r root@172.20.20.6:/home/nmonResult/ "‪C:\Users\DHCZ\Desktop\mon"')
#D:\data\DHCCZ\mon_cqs\AP\
# remote_scp('172.20.20.6','/home/nmonResult',r'D:/data/DHCCZ/task/性能测试/程序/newWars/','root','Dhcc-123@6')


# # 下载文件
#     def remote_scp(self):
#         t = paramiko.Transport(self.hostname, self.server_port)
#         t.connect(username=self.username, password=self.password)
#         p = paramiko.SFTPClient.from_transport(t)  # sftp传输
#         remote = remote_path
#         local = local_path
#         # p.get(remote,local)#下载文件
#         # p.get('/home/nmonResult',r'D:\data\DHCCZ\mon_cqs')  # 下载文件
#         # print('nmon报表已传输至本地完毕')
#
#
#         # p.put(local, remote)  # 上传文件
#         # print('nmon报表已从%s%s传输至本地%s完毕' )
#         t.close()


